#!/bin/sh
# 接收外部参数
project_name=$1
project_port=$2
project_tag=$3
target_dir=$4
acr_username=$5
acr_password=$6
acr_url=$7
acr_namespace=$8

echo "项目名称: $project_name"
echo "项目端口: $project_port"
echo "项目版本: $project_tag"
echo "目标路径: $target_dir"
echo "acr用户: $acr_username"
echo "acr密码: $acr_password"
echo "acr地址: $acr_url"
echo "acr命名空间: $acr_namespace"

# 定义退出时执行的函数
cleanup() {
    echo "执行清理操作..."
    docker logout $acr_url 2>/dev/null || true
    echo "已退出登录"
}

# 设置trap，确保在任何退出情况下都会执行cleanup
trap cleanup EXIT

# 查询容器是否存在，存在则删除
containerId=$(docker ps -a | grep -w ${project_name} | awk '{print $1}')
if [ -n "$containerId" ]; then
    # 停掉容器
    docker stop $containerId 2>/dev/null || true
    # 删除容器
    docker rm $containerId 2>/dev/null || true
    echo "成功删除旧容器"
fi

# 查询镜像是否存在，存在则删除
imageId=$(docker images | grep -w ${project_name} | awk '{print $3}')
if [ -n "$imageId" ]; then
    docker rmi -f $imageId 2>/dev/null || true
    echo "成功删除旧镜像"
fi

# 登录docker
if ! docker login --username=$acr_username -p $acr_password $acr_url; then
    echo "Docker登录失败"
    exit 1
fi

# 下载镜像
if ! docker pull $acr_url/$acr_namespace/$project_name:$project_tag; then
    echo "镜像下载失败"
    exit 1
fi

# 启动容器
if ! docker run -d -p $project_port:$project_port --network host \
  -v ${target_dir}/logs:/kujie/logs/${project_name} \
  -v /etc/localtime:/etc/localtime \
  --name $project_name \
  $acr_url/$acr_namespace/$project_name:$project_tag; then
    echo "容器启动失败"
    docker logs $project_name 2>/dev/null || echo "无法获取容器日志"
    exit 1
fi

# 检查容器是否启动成功
if docker ps | grep -q "$project_name"; then
    echo "容器启动成功"
    # 清理docker悬浮镜像
    docker image prune -f 2>/dev/null || true
    echo "已清理镜像文件"
else
    echo "容器启动失败"
    docker logs $project_name 2>/dev/null || echo "无法获取容器日志"
    exit 1
fi

# 正常退出，trap会自动执行cleanup
exit 0